// @Date         2021-11-29
// @Author       Aaron Zhang
// @Description
// @FileName      put_content.go

package template

import (
	"errors"
	"fmt"
	"os"
	"path"
	"path/filepath"
	"strings"
	"text/template"
	"zin/framework/util"
)

var funcs = template.FuncMap{"title": strings.Title}

func putContentToFileByTemplate(pName, fileName, temp, folder string, data map[string]interface{}) error {

	filePath := path.Join(folder, pName, fileName+".go")

	// check provider dir is exists
	if exists, _ := util.PathExists(filePath); exists {
		return errors.New(fmt.Sprintf("%s exists ", filePath))
	}

	//创建文件夹
	fs, _ := os.Stat(filePath)
	if fs == nil {
		err := os.MkdirAll(filepath.Dir(filePath), os.ModePerm)
		if err != nil {
			return errors.New(fmt.Sprintf("create dir failed : %v", err))
		}
	}

	fileObj, fErr := os.OpenFile(filePath, os.O_CREATE|os.O_RDWR, os.ModePerm)

	if fErr != nil {
		return errors.New(fmt.Sprintf("open file  %s failed : %v", fileName, fErr))
	}

	// 使用contractTmp模版来初始化template，并且让这个模版支持title方法，即支持{{.|title}}
	t := template.Must(template.New(fileName).Funcs(funcs).Parse(temp))
	// 将name传递进入到template中渲染，并且输出到contract.go 中
	if err := t.Execute(fileObj, data); err != nil {
		return err
	}
	FileArr = append(FileArr, filePath)
	return nil
}
